<template>
  <div class="literature-detail" v-loading="loading">
    <div class="header">
      <el-button @click="$router.go(-1)" round>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <div class="actions">
        <el-button 
          :type="literature.isFavorite ? 'warning' : 'success'" 
          @click="toggleFavorite"
          round
        >
          <el-icon><Star v-if="literature.isFavorite" /><StarFilled v-else /></el-icon>
          {{ literature.isFavorite ? '取消收藏' : '收藏' }}
        </el-button>
        <el-button type="primary" @click="downloadFile" round>
          <el-icon><Download /></el-icon>
          下载文献
        </el-button>
      </div>
    </div>

    <div class="content" v-if="literature.id">
      <!-- 基本信息 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
        </template>
        <el-descriptions :column="2" border size="medium">
          <el-descriptions-item label="标题" :span="2">
            <span class="title-text">{{ literature.title }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="作者">
            {{ literature.authors }}
          </el-descriptions-item>
          <el-descriptions-item label="发表日期">
            {{ formatDate(literature.publicationDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="期刊">
            {{ literature.journal }}
          </el-descriptions-item>
          <el-descriptions-item label="DOI">
            <el-link 
              v-if="literature.doi" 
              :href="'https://doi.org/' + literature.doi" 
              target="_blank"
              type="primary"
            >
              {{ literature.doi }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag type="info">{{ literature.fileType?.toUpperCase() }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="识别状态">
            <el-tag :type="getRecognitionStatusType(literature.recognitionStatus)">
              {{ getRecognitionStatusText(literature.recognitionStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="上传时间" :span="2">
            {{ formatDate(literature.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="关键词" :span="2">
            <div class="keyword-tags">
              <el-tag 
                v-for="keyword in literature.keywords?.split(',')" 
                :key="keyword" 
                size="small" 
                type="success"
                effect="dark"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ keyword.trim() }}
              </el-tag>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 摘要 -->
      <el-card class="abstract-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>摘要</h3>
          </div>
        </template>
        <div class="abstract-content">
          <p class="abstract-text">{{ literature.abstractText || '暂无摘要信息' }}</p>
        </div>
      </el-card>

      <!-- 文献内容预览 -->
      <el-card class="content-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>文献内容</h3>
            <el-switch 
              v-model="showFullContent" 
              active-text="显示全文" 
              inactive-text="显示摘要"
              inline-prompt
            />
          </div>
        </template>
        <div class="content-preview">
          <div v-if="literature.fileType === 'pdf'" class="pdf-content">
            <div class="pdf-placeholder">
              <el-icon size="60" color="#409eff"><Document /></el-icon>
              <p>PDF文件预览（点击下载查看完整内容）</p>
            </div>
          </div>
          <div v-else-if="literature.fileType === 'text'" class="text-content">
            <pre v-if="showFullContent">{{ literature.abstractText }}</pre>
            <p v-else>{{ literature.abstractText }}</p>
          </div>
          <div v-else class="other-content">
            <p>该文件类型暂不支持在线预览</p>
          </div>
        </div>
      </el-card>

      <!-- 统计信息 -->
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>统计信息</h3>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6" :xs="12">
            <div class="stat-item">
              <div class="stat-value">{{ literature.keywords?.split(',').length || 0 }}</div>
              <div class="stat-label">关键词数量</div>
            </div>
          </el-col>
          <el-col :span="6" :xs="12">
            <div class="stat-item">
              <div class="stat-value">{{ literature.fileSize ? formatFileSize(literature.fileSize) : '-' }}</div>
              <div class="stat-label">文件大小</div>
            </div>
          </el-col>
          <el-col :span="6" :xs="12">
            <div class="stat-item">
              <div class="stat-value">{{ getDaysSinceUpload(literature.createTime) }}</div>
              <div class="stat-label">上传天数</div>
            </div>
          </el-col>
          <el-col :span="6" :xs="12">
            <div class="stat-item">
              <div class="stat-value">{{ literature.isFavorite ? '已收藏' : '未收藏' }}</div>
              <div class="stat-label">收藏状态</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 相关文献推荐 -->
      <el-card class="related-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>相关文献推荐</h3>
          </div>
        </template>
        <div v-if="relatedLiterature.length > 0" class="related-content">
          <el-row :gutter="20">
            <el-col 
              v-for="related in relatedLiterature" 
              :key="related.id" 
              :span="8" 
              :xs="24" 
              :sm="12"
              class="related-item-col"
            >
              <el-card class="related-item" @click="viewRelated(related.id)" shadow="hover">
                <h4 class="related-title">{{ related.title }}</h4>
                <p class="related-author">{{ related.authors }}</p>
                <p class="related-journal">{{ related.journal }}</p>
                <p class="related-date">{{ formatDate(related.publicationDate) }}</p>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <div v-else class="empty-related">
          <el-empty description="暂无相关文献推荐" :image-size="80" />
        </div>
      </el-card>
    </div>
    
    <div v-else class="empty-content">
      <el-empty description="未找到文献信息" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Download, Document, Star, StarFilled } from '@element-plus/icons-vue'
import { literatureApi } from '@/api/literature'
import type { Literature } from '@/api/literature'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showFullContent = ref(false)

const literature = reactive<Literature>({
  id: 0,
  title: '',
  authors: '',
  abstractText: '',
  keywords: '',
  journal: '',
  publicationDate: '',
  doi: '',
  fileName: '',
  fileSize: 0,
  fileType: '',
  status: 0,
  recognitionStatus: 0,
  uploadUserId: 0,
  uploadUserName: '',
  createTime: '',
  updateTime: '',
  isFavorite: false
})

const relatedLiterature = ref<Literature[]>([])

// 方法
const loadLiteratureDetail = async () => {
  loading.value = true
  try {
    const id = Number(route.params.id)
    const data: Literature = await literatureApi.getById(id)
    Object.assign(literature, data)
    loading.value = false
  } catch (error) {
    ElMessage.error('加载文献详情失败')
    loading.value = false
  }
}

const toggleFavorite = async () => {
  try {
    await literatureApi.toggleFavorite(literature.id!)
    literature.isFavorite = !literature.isFavorite
    ElMessage.success(literature.isFavorite ? '收藏成功' : '取消收藏成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const downloadFile = async () => {
  try {
    await literatureApi.download(literature.id!)
    ElMessage.success('文件下载成功')
  } catch (error) {
    ElMessage.error('文件下载失败')
  }
}

const viewRelated = (id: number) => {
  router.push(`/literature/detail/${id}`)
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  try {
    // 更健壮的日期解析方法
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) {
      // 尝试其他常见日期格式
      const isoDate = new Date(dateStr.replace(' ', 'T'))
      if (!isNaN(isoDate.getTime())) {
        return isoDate.toLocaleDateString('zh-CN')
      }
      return dateStr // 如果所有方法都失败，返回原始字符串
    }
    return date.toLocaleDateString('zh-CN')
  } catch (e) {
    // 如果解析失败，尝试直接返回原始字符串
    return dateStr || '-'
  }
}

const formatFileSize = (size: number) => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  return (size / (1024 * 1024)).toFixed(2) + ' MB'
}

const getDaysSinceUpload = (dateStr: string) => {
  if (!dateStr) return '-'
  try {
    const uploadDate = new Date(dateStr)
    if (isNaN(uploadDate.getTime())) {
      // 尝试其他常见日期格式
      const isoDate = new Date(dateStr.replace(' ', 'T'))
      if (isNaN(isoDate.getTime())) {
        return '-'
      }
      const today = new Date()
      const diffTime = Math.abs(today.getTime() - isoDate.getTime())
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return diffDays + ' 天'
    }
    const today = new Date()
    const diffTime = Math.abs(today.getTime() - uploadDate.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays + ' 天'
  } catch (e) {
    return '-'
  }
}

const getRecognitionStatusType = (status: number) => {
  // 修改状态1和状态2都显示为已识别的样式
  if (status === 1 || status === 2) {
    return 'success' // 已识别的绿色样式
  }
  
  const types = ['', 'success', 'warning', 'danger']
  return types[status] || ''
}

const getRecognitionStatusText = (status: number) => {
  // 修改状态1和状态2都显示为已识别的文本
  if (status === 1 || status === 2) {
    return '已识别'
  }
  
  const texts = ['待处理', '已识别', '识别中', '识别失败']
  return texts[status] || '未知'
}

// 生命周期
onMounted(() => {
  loadLiteratureDetail()
})
</script>

<style scoped>
.literature-detail {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.content > .el-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.title-text {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.keyword-tags {
  max-height: 100px;
  overflow-y: auto;
  padding: 5px 0;
}

.abstract-content {
  line-height: 1.6;
}

.abstract-text {
  text-align: justify;
  font-size: 14px;
  color: #666;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

.content-preview {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pdf-placeholder {
  text-align: center;
  color: #909399;
}

.pdf-placeholder p {
  margin-top: 10px;
}

.text-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

.other-content {
  text-align: center;
  color: #909399;
  padding: 50px 0;
}

.stats-card {
  border-radius: 10px;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.related-content {
  padding: 10px 0;
}

.related-item-col {
  margin-bottom: 20px;
}

.related-item {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.related-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.related-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.related-author {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.related-journal {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #909399;
}

.related-date {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.empty-related, .empty-content {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .literature-detail {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .actions {
    justify-content: center;
  }
  
  .stat-item {
    padding: 10px 0;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style>